<template>
  <div>
    <el-breadcrumb separator-icon="ArrowRight" style="margin: 16px">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色管理</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card style="margin: 15px; min-height: calc(100vh - 111px)">
      <div>
        <!-- 功能区 -->
        <div style="margin: 10px 0">
          <!-- 搜索区 -->
          <div style="margin: 10px 0">
            <el-input
              v-model="search"
              clearable
              placeholder="用户角色id"
              prefix-icon="Search"
              style="width: 20%"
            />
            <el-button
              icon="Search"
              style="margin-left: 5px"
              type="primary"
              @click="load"
            ></el-button>
            <el-button
              icon="refresh-left"
              style="margin-left: 10px"
              type="default"
              @click="reset"
            ></el-button>
            <div style="float: right">
              <el-tooltip content="添加" placement="top">
                <el-button
                  icon="plus"
                  style="width: 50px"
                  type="primary"
                  @click="add"
                ></el-button>
              </el-tooltip>
            </div>
          </div>
        </div>

        <!-- 表格 -->
        <el-table
          v-loading="loading"
          :data="tableData"
          border
          max-height="705"
          style="width: 100%"
        >
          <el-table-column label="角色ID" prop="id" />
          <el-table-column label="角色名称" prop="roleName" />
          <el-table-column label="角色标识符" prop="roleType" />
          <el-table-column label="角色描述" prop="remark" />
          <el-table-column label="创建时间" prop="createTime" />
          <el-table-column label="更新时间" prop="updateTime" />
          <!--      操作栏-->
          <el-table-column v-if="role != 'stu'" label="操作" width="300px">
            <template #default="scope">
              <el-button
                icon="Edit"
                type="primary"
                @click="handleEdit(scope.row)"
              ></el-button>

              <el-button
                icon="Edit"
                type="primary"
                @click="assignBtn(scope.row)"
                >分配权限</el-button
              >

              <el-popconfirm
                title="确认删除？"
                @confirm="handleDelete(scope.row.id)"
              >
                <template #reference>
                  <el-button icon="Delete" type="danger"></el-button>
                </template>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页 -->
        <!-- <div style="margin: 10px 0">
          <el-pagination
            v-model:currentPage="currentPage"
            :page-size="pageSize"
            :page-sizes="[10, 20]"
            :total="total"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handlePageSizeChange"
            @current-change="handleCurrentPageChange"
          />
        </div> -->
        <!--      弹窗-->
        <div>
          <el-dialog
            v-model="dialogVisible"
            title="操作"
            width="30%"
            @close="cancel"
          >
            <el-form
              ref="form"
              :model="form"
              :rules="rules"
              label-width="120px"
            >
              <el-form-item label="角色ID" prop="id">
                <el-input
                  v-model="form.id"
                  placeholder="输入角色ID"
                  clearable
                  style="width: 80%"
                ></el-input>
              </el-form-item>
              <el-form-item label="角色名称" prop="roleName">
                <el-input
                  v-model="form.roleName"
                  placeholder="输入角色名称"
                  clearable
                  style="width: 80%"
                ></el-input>
              </el-form-item>
              <el-form-item label="角色标识符" prop="roleType">
                <el-input
                  v-model="form.roleType"
                  placeholder="输入角色标识符"
                  clearable
                  style="width: 80%"
                ></el-input>
              </el-form-item>
              <el-form-item label="角色描述" prop="remark">
                <el-input
                  v-model="form.remark"
                  placeholder="输入角色描述"
                  clearable
                  style="width: 80%"
                ></el-input>
              </el-form-item>
            </el-form>
            <template #footer>
              <span class="dialog-footer">
                <el-button @click="cancel">取 消</el-button>
                <el-button type="primary" @click="save">确 定</el-button>
              </span>
            </template>
          </el-dialog>
        </div>

        <!-- 分配权限弹窗 -->
        <!--      弹窗-->
        <div>
          <el-dialog
            v-model="dialogVisible2"
            :title="assignDialog.title"
            width="30%"
            @close="cancel2"
          >
            <el-tree
              ref="assignTree"
              style="max-width: 600px"
              :data="assignTreeData"
              node-key="id"
              :props="defaultProps"
              empty-text="暂无数据"
              :show-checkbox="true"
              default-expand-all
              :default-checked-keys="assignTreeChecked"
            />
            <template #footer>
              <span class="dialog-footer">
                <el-button @click="cancel2">取 消</el-button>
                <el-button type="primary" @click="assignConfrim"
                  >确 定</el-button
                >
              </span>
            </template>
          </el-dialog>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script>
import request from "@/utils/request";
import { ro } from "element-plus/es/locale";
const { ElMessage } = require("element-plus");

export default {
  data() {
    return {
      defaultProps: {
        children: "children",
        label: "title",
      },
      loading: true, // 控制加载状态
      disabled: false, // 是否禁用某些表单项
      judge: false, // 判断当前是新增还是编辑状态
      dialogVisible: false, // 控制弹窗显示状态
      dialogVisible2: false, // 控制弹窗显示状态
      search: "", // 搜索框的内容
      currentPage: 1, // 当前页数
      pageSize: 10, // 每页显示的数据条数
      total: 0, // 数据的总条数
      tableData: [], // 存放表格数据
      form: {}, // 存放表单数据
      assignTree: [],
      date: [], // 用于存放日期筛选范围
      rules: {
        // 表单校验规则
        id: [{ required: true, message: "角色ID不能为空", trigger: "blur" }],
        roleName: [
          { required: true, message: "角色名称不能为空", trigger: "blur" },
        ],
        roleType: [
          { required: true, message: "角色标识符不能为空", trigger: "blur" },
        ],
        remark: [
          { required: true, message: "角色描述不能为空", trigger: "blur" },
        ],
      },
      //分配权限弹框属性
      assignDialog: {
        title: "",
      },
      roleId: "",
      // 树的数据
      assignTreeData: [],
      //角色原来的权限
      assignTreeChecked: [],
      datarole: {
        roleId: "",
        list: "",
      },
    };
    user: {
    }
  },
  created() {
    // 获取当前用户的角色信息
    this.role = JSON.parse(window.sessionStorage.getItem("identity"));
    this.user = JSON.parse(window.sessionStorage.getItem("user"));
    console.log("12", JSON.parse(window.sessionStorage.getItem("user")));

    // 加载数据
    this.load();
    this.loading = true;
    setTimeout(() => {
      // 设置延迟执行
      this.loading = false;
    }, 1000);
  },
  methods: {
    // 加载数据的方法
    async load() {
      request
        .get("/role/find", {
          params: {
            pageNum: this.currentPage, // 当前页码
            pageSize: this.pageSize, // 每页显示的条数
            search: this.search, // 搜索关键字
          },
        })
        .then((res) => {
          console.log(res);
          this.tableData = res.data.records; // 表格数据
          this.total = res.data.total; // 总条数
          this.loading = false; // 关闭加载状态
        });
    },
    //分配权限树回显
    async getAssingShow(row) {
      request
        .get(`/role/getAssingShow/${this.user.userId}/${row.id}`)
        .then((res) => {
          console.log("1111", res);
          this.assignTreeData = res.data.menuList;
          console.log("assignTreeData", this.assignTreeData);
          // 1. 获取原始勾选列表
          const checkList = res.data.checkList;
          // 2. 过滤出叶子节点（没有子节点的节点）
          this.assignTreeChecked = this.filterLeafNodes(
            checkList,
            this.assignTreeData
          );
          console.log("处理后勾选节点（仅叶子节点）:", this.assignTreeChecked);
          this.loading = false;
          this.loading = false; // 关闭加载状态
        });
    },
    filterLeafNodes(checkList, treeData) {
      const leafNodes = [];
      // 递归检查节点是否是叶子节点
      const checkNode = (nodes) => {
        nodes.forEach((node) => {
          if (checkList.includes(node.id)) {
            // 如果是叶子节点（没有子节点），加入结果
            if (!node.children || node.children.length === 0) {
              leafNodes.push(node.id);
            }
          }
          // 继续递归检查子节点
          if (node.children) {
            checkNode(node.children);
          }
        });
      };
      checkNode(treeData);
      return leafNodes;
    },

    //查询回显数据
    checked(id, data, newArr) {
      data.forEach((item) => {
        if (item.id == id) {
          if (item.children && item.children.length == 0) {
            // 只有没有子节点时，才加入选中列表
            newArr.push(item.id);
          } else {
            if (item.children && item.children.length != 0) {
              //递归调用
              this.checked(id, item.children, newArr);
            }
          }
        }
      });
    },

    //分配权限按钮
    async assignBtn(row) {
      //清空数据
      this.roleId = "";
      this.assignTreeData = [];
      this.assignTreeChecked = [];
      this.assignDialog.title = "为【" + row.roleName + "】分配权限";
      console.log(row);
      this.roleId = row.id;
      this.dialogVisible2 = true; // 控制弹窗显示状态
      //获取权限树数据
      this.getAssingShow(row);
      //获取权限树回显

      console.log(this.roleId);
    },
    //添加权限接口
    //权限分配确定按钮
    async assignConfrim() {
      console.log(this.$refs.assignTree.getCheckedKeys());
      console.log(this.$refs.assignTree.getHalfCheckedKeys());
      const ids = this.$refs.assignTree
        .getCheckedKeys()
        .concat(this.$refs.assignTree.getHalfCheckedKeys());

      console.log(ids);
      this.datarole.roleId = this.roleId;
      this.datarole.list = ids;
      request.post("/role/saveRoleMenu", this.datarole).then((res) => {
        console.log(res);
        this.dialogVisible2 = false; // 关闭弹窗
        this.loading = false; // 关闭加载状态
      });
    },
    // 重置搜索框和日期范围
    reset() {
      this.search = "";
      this.date = [];
      request
        .get("/role/find", {
          params: {
            pageNum: 1, // 重新加载第一页
            pageSize: this.pageSize,
            search: this.search,
          },
        })
        .then((res) => {
          console.log(res);
          this.tableData = res.data.records; // 更新表格数据
          this.total = res.data.total; // 更新总条数
          this.loading = false; // 关闭加载状态
        });
    },
    // 取消操作
    cancel() {
      this.$refs.form.resetFields(); // 重置表单
      this.dialogVisible = false; // 关闭弹窗
    },
    // 取消操作
    cancel2() {
      console.log("Cancel button clicked");
      this.dialogVisible2 = false; // 关闭弹窗
      console.log("dialogVisible2 set to:", this.dialogVisible2);
    },
    // 显示添加弹窗
    add() {
      this.dialogVisible = true;
      this.$nextTick(() => {
        this.$refs.form.resetFields(); // 重置表单
        this.disabled = false; // 启用表单项
        this.form = {}; // 清空表单数据
        this.judge = false; // 设置为新增状态
      });
    },
    // 保存数据
    save() {
      this.$refs.form.validate(async (valid) => {
        if (valid) {
          if (this.judge === false) {
            // 新增
            const res = await request.post("/role/add", this.form);
            console.log(res);
            if (res.code === "0") {
              ElMessage({
                message: "新增成功", // 提示信息
                type: "success",
              });
              this.dialogVisible = false; // 关闭弹窗
              this.load(); // 重新加载数据
            } else {
              ElMessage({
                message: res.msg, // 错误提示信息
                type: "error",
              });
            }
          } else {
            // 修改
            const res = await request.put("/role/update", this.form);
            console.log(res);
            if (res.code === "0") {
              ElMessage({
                message: "修改成功", // 提示信息
                type: "success",
              });
              this.dialogVisible = false; // 关闭弹窗
              this.load(); // 重新加载数据
            } else {
              ElMessage({
                message: res.msg, // 错误提示信息
                type: "error",
              });
            }
          }
        }
      });
    },
    // 取消操作
    cancel() {
      this.$refs.form.resetFields(); // 重置表单
      this.dialogVisible = false; // 关闭弹窗
    },
    // 编辑操作
    handleEdit(row) {
      // 设置为编辑状态
      this.judge = true;
      this.dialogVisible = true;
      this.$nextTick(() => {
        this.$refs.form.resetFields(); // 重置表单
        this.form = JSON.parse(JSON.stringify(row)); // 复制当前行数据
        this.disabled = true; // 禁用表单项
      });
    },
    // 删除操作
    async handleDelete(id) {
      console.log(id);
      request.delete("/role/delete/" + id).then((res) => {
        if (res.code === "0") {
          ElMessage({
            message: "删除成功", // 提示信息
            type: "success",
          });
          this.search = ""; // 清空搜索框
          this.load(); // 重新加载数据
        } else {
          ElMessage({
            message: res.msg, // 错误提示信息
            type: "error",
          });
        }
      });
    },
    handlePageSizeChange(val) {
      this.pageSize = val;
      this.fetchData();
    },

    handleCurrentPageChange(val) {
      this.currentPage = val;
      this.fetchData();
    },
  },
};
</script>

<style scoped>
.el-button {
  margin-left: 10px;
}
</style>